package com.eascs.banknet.boc.service.trans;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.jdom.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.banknet.boc.base.BOCUtil;
import com.eascs.banknet.boc.dao.BOC003Dao;
import com.eascs.banknet.boc.service.BOCAbstractService;
import com.eascs.banknet.boc.vo.boc003.BOC003Element;
import com.eascs.banknet.boc.vo.boc003.BOC003Root;
import com.eascs.banknet.common.utils.XmlHelp;
import com.eascs.banknet.constant.EAContant;
import com.eascs.banknet.log.entity.LogEntity;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;

/**
 * 查询放款信息
 * @author Administrator
 *
 */
@Service("boc003Service")
public class BOC003Service extends BOCAbstractService{
	private static final Logger logger = LoggerFactory.getLogger(BOC003Service.class);
	
	@Autowired
	private BOC003Dao boc003Dao;
	
	@Autowired
	private BOCUtil bocUtil;
	
	private String startId;
	
	@SuppressWarnings("unchecked")
	@Override
	public Map<String, String> dowork() {
		String id = System.currentTimeMillis()+"";
		LogEntity logEntity = initLogData();
		try {
			logger.info("查询放款信息调用开始，startId:[{}]......", startId);
			/**
			 * 查询数据，组装请求xml(批量处理，每次最多100条)
			 */
			List<BOC003Element> dataList = boc003Dao.queryData(startId);
			if(dataList.isEmpty()){
				startId = null;
				logger.info("查询放款信息,没有符合条件的数据");
				return null;
			}
			//请求组装xml消息
			BOC003Root root = new BOC003Root();
			root.getBody().setList(dataList);
			String xml =  XmlHelp.convertToXml(root);
			//保存xml到ftp服务器
			XmlHelp.createXml("003" + "(" + id + ")", id + "&" + xml, "BOC003RQ", bocUtil.getEaFtpInfo());
			
			/*
			 * 调用中行接口
			 */
			logger.info("组装请求数据完成，开始调用中行003接口, xml:{}", xml);
			String returnXml = bocNetService.executeSocket(bocUtil.getBocSocketInfo(),  "003", null, xml);
			if(StringUtil.isEmpty(returnXml)){
				logger.error("中行003接口返回数据为空！");
				throw new Exception("中行003接口返回数据为空, appno:");
			}
			logger.info("中行003接口返回xml完成, returnXml：{}", returnXml);
			
			/*
			 * 解析返回xml，保存数据
			 */
			XmlHelp.createXml("003"+"("+id+")",returnXml,"BOC003RS", bocUtil.getEaFtpInfo());
			 //解析服务器返回的XML
			Element rsRoot = XmlHelp.getRootByString(returnXml);
			Element head = rsRoot.getChild("HEADER");
			String trncod_rs = head.getChildText("RETCODE")==null?"":head.getChildText("RETCODE");
			if (!EAContant.BOC001RS.equals(trncod_rs.toLowerCase())) {
				throw new Exception(rsRoot.getChildText("NOTE"));
			}
			Document doc = DocumentHelper.parseText(returnXml);
			org.dom4j.Element node = doc.getRootElement();
			org.dom4j.Element body = node.element("BODY");
			org.dom4j.Element output = body.element("OUTPUT");
			//获取xml主数据贷款流水状态
			List<org.dom4j.Element> outputList = output.elements("LOANINFO");
			if (!outputList.isEmpty()){
				for (org.dom4j.Element element : outputList) {
					 String appno = element.elementText("APPNO");//申请编号
					 String loanapplyNo = loanapplyDao.getLoanapplyNoByAppno(appno);
					 String actno = element.elementText("ACTNO");//贷款账号
					 String loan_flg = element.elementText("LOAN_FLG");//放款标示
					 String loan_amt = element.elementText("LOAN_AMT");//贷款金额
					 String rate = element.elementTextTrim("RATE");//利率
					 
					 //年化利率/100
					 BigDecimal hundred = BigDecimal.valueOf(100L);
					 BigDecimal loanrate = new BigDecimal(rate);	
					 loanrate = loanrate.divide(hundred, 4, BigDecimal.ROUND_HALF_DOWN);
					 
					 String fadat = element.elementText("FADAT");//放款日期
					 Date fadate = DateUtils.formateStandDate(fadat.substring(0,4)+"-"+fadat.substring(4, 6)+"-"+fadat.substring(6,8));
					 String lafterm = element.elementText("LAFTERM");//贷款期限
					 String maturityDate = element.elementText("MATURITY_DATE");//到期日
					 Date endBankDate = DateUtils.formateStandDate(maturityDate.substring(0,4)+"-"+maturityDate.substring(4, 6)+"-"+maturityDate.substring(6,8));
					 
					 logger.info("返回信息,appno:{}, actno:{}, loan_flg:{}", appno, actno, loan_flg);
					 if("Y".equals(loan_flg)){
						 logger.info("返回放款信息,appno:{}, actno:{}, loan_flg:{}, loan_amt:{}, loanrate:{}, fadat:{}, lafterm:{},maturityDate:{}", 
								 appno, actno, loan_flg, loan_amt, loanrate, fadat, lafterm,maturityDate);
						 boc003Dao.updateInfo(appno, loanapplyNo, loan_amt, loanrate, loan_flg, lafterm, actno, fadate,endBankDate);
						 logService.writeLog(logEntity, appno, LogEntity.RESULT_TYPE_SUCCESS, null);
					 }
				}
			}
			logger.info("查询放款信息成功");
		} catch (Exception e) {
			logger.error("查询放款信息出现异常，errMsg：[{}]", e);
			logService.writeLog(logEntity, id, LogEntity.RESULT_TYPE_ERROR, e.getMessage());
		}
		return null;
	}
	
	@Override
	public LogEntity initLogData() {
		LogEntity logEntity = new LogEntity();
		logEntity.setBankType(LogEntity.BANK_TYPE_BOC);
		logEntity.setTransType("003");
		logEntity.setTypeName("查询放款信息");
		logEntity.setStartTime(new Date());
		return logEntity;
	}
}
